package edu.zut.main.thread;

public class ThreadSleep2 {
    public static void main(String[] args) {
        //sale是被多个窗口共享的，要保证不管哪个窗口都操作的是这一个sale
        Sale sale = new Sale();
        SaleTicket saleTicket = new SaleTicket(sale);
        SaleTicket saleTicket2 = new SaleTicket(sale);
        SaleTicket saleTicket3 = new SaleTicket(sale);

        Thread thread = new Thread(saleTicket, "小明");
        Thread thread2 = new Thread(saleTicket2, "小李");
        Thread thread3 = new Thread(saleTicket3, "小花");
        thread.start();
        thread2.start();
        thread3.start();
    }

}
//模拟多个窗口同时售票时，如果出现延迟
class SaleTicket implements Runnable{


    Sale sale;
    public SaleTicket(Sale sale) {
        this.sale = sale;
    }

    //售票任务
    @Override
    public void run() {

        while (true){
            //同步代码块实现资源的加锁，保证同步资源每次只能由一个线程访问，不管是否出现阻塞
            //同步代码块中 需要指定锁定的对象   因为我们的操作都属于对象的
//            synchronized (sale){
                if (sale.getTicketNum() <= 0) {
                    System.out.println(Thread.currentThread().getName() + "余票不足");
                    break;
                }
                sale.saleTicket();
//            }
        }
    }
}

class Sale{
    //余票
    private int ticketNum = 10;

    //同步方法   保证当前方法在多线程中，每次只能被一个线程获取操作
    //同步方法的本质依然还是锁定对象
    public synchronized int getTicketNum() {
        return ticketNum;
    }
    //售票操作
    public synchronized void saleTicket(){

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "售出了第"+ticketNum-- + "张票");
    }
}


